import serial
import time
import serial.tools.list_ports
from tkinter import Text
# 配置串口参数  
port = 'COM5'  # 在Windows上通常是COMx，在Linux和macOS上通常是/dev/ttyUSBx或/dev/ttySx  
baudrate = 115200  # 波特率  
timeout = 0.15  # 读超时时间（秒）  

def send_data(ser,data):
    for str in data:
        ser.write(str.encode("utf-8"))  
        data_received = ser.readline()
    ser.write(b'\r')
    data_received = ser.readlines()
    if len(data_received) >= 2:
        return data+"\tOutPut:\n"+"".join([i.decode("utf-8") for i in data_received[1:-1]])
    else:
        return ""

def ip_config_read(root,port,Text:Text):
    ser = serial.Serial(port, baudrate, timeout=timeout)
    try:
        if ser.is_open: 
            ser.write(b'\r')
            data_received = ser.readline()
            print(f"串口 {port} 已打开")
            Text.insert("1.0",f"串口 {port} 已打开\n")
            root.update()
        Text.insert("1.0",send_data(ser,"ip"))
        root.update()
    except serial.SerialException as e:  
        print(f"串口错误: {e}")  
    finally:  
        # 关闭串口  
        if ser.is_open:  
            ser.close()  
            print(f"串口 {port} 已关闭")
            Text.insert("1.0",f"串口 {port} 已关闭\n")
            root.update() 
    
def ip_config(root,ip,port,Text:Text): 
    ser = serial.Serial(port, baudrate, timeout=timeout)
    if ser.is_open: 
        ser.write(b'\r')
        data_received = ser.readline()
        print(f"串口 {port} 已打开")
        Text.insert("1.0",f"串口 {port} 已打开\n")
        root.update()
    try:  
        Text.insert("1.0",send_data(ser,"ip"))
        root.update()
        Text.insert("1.0",send_data(ser,"init erase"))
        root.update()
        Text.insert("1.0",send_data(ser,"init add ip set {}".format(ip)))
        root.update()
        Text.insert("1.0",send_data(ser,"init add eb setip {}".format(ip)))
        root.update()
        Text.insert("1.0",send_data(ser,"init add mode slave"))
        root.update()
        Text.insert("1.0",send_data(ser,"init add ptp start"))
        root.update()
        Text.insert("1.0",send_data(ser,"init boot"))
        root.update()
        Text.insert("1.0",send_data(ser,"ip"))
        root.update()
        
    except serial.SerialException as e:  
        print(f"串口错误: {e}")  
    
    finally:  
        # 关闭串口  
        if ser.is_open:  
            ser.close()  
            print(f"串口 {port} 已关闭")
            Text.insert("1.0",f"串口 {port} 已关闭\n")
            root.update()

def port_list():
    ports_list = list(serial.tools.list_ports.comports())
    if len(ports_list) <= 0:
        return {}
    else:
        results = {}
        for i in ports_list:  
            results[i[1]] = i[0]
        return results